package com.app.couponsharelife.ui.adapter

import androidx.databinding.DataBindingUtil
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.databinding.FeedbackListItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener

/**
 * Created by guluwa on 2018/11/24.
 */
class FeedbackPicsListAdapter(val list: MutableList<String>,
                              private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    fun addData(pic: String, index: Int) {
        if (index != -1)
            list[index] = pic
        if (list.size <= 3)
            list.add("")
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.feedback_list_item, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        holder as ViewHolder
        if (list[position] == "") {
            holder.databinding.ivFeedBack.visibility = View.GONE
            holder.databinding.ivDeletePic.visibility = View.GONE
        } else {
            Glide.with(holder.itemView).asBitmap()
                    .apply(RequestOptions().centerCrop())
                    .load(list[position])
                    .into(holder.databinding.ivFeedBack)
            holder.databinding.ivFeedBack.visibility = View.VISIBLE
            holder.databinding.ivDeletePic.visibility = View.VISIBLE
        }
    }

    inner class ViewHolder(val databinding: FeedbackListItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.ivDeletePic.setOnClickListener {
                if (adapterPosition != -1) {
                    list.removeAt(adapterPosition)
                    notifyDataSetChanged()
                }
            }
            databinding.root.setOnClickListener {
                if (adapterPosition != -1) {
                    listener.click(adapterPosition, list[adapterPosition])
                }
            }
        }
    }
}